import cloud from "@lafjs/cloud";

const db = cloud.database();
import { resultOk, hashPassword, resultFail } from "@/utils";
const adminDbName = "admin-staff";
export async function main(ctx: FunctionContext) {
  const { username, password } = ctx.body;
  if (!username || !password) return resultFail("账号和密码不可为空");

  const { data: admin } = await db
    .collection(adminDbName)
    .where({ username })
    .withOne({
      query: db.collection("password").where({ type: "login" }),
      localField: "_id",
      foreignField: "uid",
      as: "password"
    })
    .getOne();
  // check username and password
  const isMatchPassword = admin.password?.password === hashPassword(password);
  if (!admin || !isMatchPassword) return resultFail("账号或密码错误");

  // 默认 token 有效期为 7 天
  const expire = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7;
  delete admin["password"];
  delete admin["created_at"];
  delete admin["updated_at"];
  const payload = {
    uid: admin._id,
    ...admin,
    type: "admin",
    exp: expire
  };

  const access_token = cloud.getToken(payload);
  return resultOk({
    ...admin,
    accessToken: access_token,
    uid: admin._id,
    expire
  });
}
